<template>
	<view class="user-pages-choose-index" :style="{background:pageColor}" v-if="isLoad">

		<!-- #ifndef H5 -->
		<uni-nav-bar :fixed="true" :shadow="false" :statusBar="true" leftIcon="icon-left" title="选择服务地址" color="#000"
			backgroundColor="">
		</uni-nav-bar>
		<!-- #endif -->

		<fixed>
			<view class="fill-base">
				<!-- #ifndef H5 -->
				<image class="abs choose-bg" :src="`https://api.huixuananmm.com/admin/anmo/mine/choose-addr-bg.png`"></image>
				<view :style="{height:`${configInfo.navBarHeight}px`}"></view>
				<!-- #endif -->
				<view class="flex-between fill-base pd-lg rel" style="border-radius: 40rpx 40rpx 0 0;">
					<view
						@tap.stop="$util.goUrl({url:`/user/pages/choose/city?type=${options.type}`,openType:`redirectTo`})"
						class="flex-y-center">
						<view class="ellipsis" style="max-width: 130rpx;">{{city_info | handleCityText}}</view>
						<i class="iconfont icon-down" style="transform: scale(0.5);"></i>
					</view>
					<view @tap.stop="$util.goUrl({url:`/user/pages/choose/addr?type=${options.type}`})"
						class="flex-1 ml-md">
						<search type="input" :padding="0" textAlign="left" :confirmSearch="true" :radius="30"
							height="70rpx" :placeholder="(city_info&&!city_info.id)?`请搜索城市/区/县+地点`:`请搜索城市/区/县/地点`">
						</search>
					</view>
				</view>
			</view>
		</fixed>

		<view @tap.stop="toResetLoca(0)" class="fill-base mt-md ml-md mr-md radius-16" style="padding: 28rpx 30rpx;">
			<view class="flex-between">
				<view class="flex-y-center f-desc c-paragraph"><i class="iconfont icondingwei1 mr-sm"
						style="font-size: 40rpx;" :style="{color:primaryColor}"></i>
					<view class="text-bold">当前选择</view>
				</view>
				<view @tap.stop="toResetLoca(1)" class="flex-y-center f-caption" :style="{color:primaryColor}"><i
						class="iconfont iconqiehuandaodingwei" style="margin-right: 6rpx;"></i>
					<view class="text-bold">刷新定位</view>
				</view>
			</view>
			<view class="f-paragraph c-black text-bold mt-md">{{location | handleAddrText}}</view>
		</view>
		<view class="fill-base mt-md ml-md mr-md pl-lg pr-lg radius-16">
			<view class="flex-between f-desc c-paragraph" style="padding: 40rpx 0;">
				<view>常用服务地址</view>
				<view
					@tap.stop="$util.toCheckLogin({url:`/user/pages/address/list?check=2&type=${options.type}`, openType:`redirectTo`})"
					class="flex-y-center">
					{{!userInfo || (userInfo && !userInfo.nickName)?'立即登录':address_list&&address_list.length>0?'查看全部':'添加地址'}}<i
						class="iconfont icon-right text-bold"></i>
				</view>
			</view>
			<view @tap.stop="toSelectAddr(index)" class="f-paragraph b-1px-t" style="padding: 34rpx 0;"
				v-for="(item,index) in address_list" :key="index">
				<view class="c-black text-bold">{{`${item.address} ${item.address_info}`}}</view>
				<view class="flex-y-center mt-sm" style="color: #090909;">{{item.user_name}}
					<view class="ml-md">{{item.mobile}}</view>
					<view class="default-btn flex-center f-caption ml-md rel"
						:style="{borderColor:primaryColor,color:primaryColor}" v-if="item.status ==1">
						<view class="default-btn abs" :style="{background:primaryColor}"></view>
						默认
					</view>
				</view>
			</view>
		</view>
		<view class="fill-base mt-md ml-md mr-md pl-lg pr-lg radius-16">
			<view class="f-desc c-paragraph" style="padding: 40rpx 0;">
				热门城市
			</view>
			<view class="flex-1 f-desc c-warning pb-md" v-if="city_list&&city_list.length==0">后台设置推荐城市即可展示热门城市</view>
			<view class="flex-warp" style="padding-bottom: 15rpx;">
				<view @tap.stop="toSelectCity(index)" class="list-item flex-center f-desc c-paragraph mr-md mb-md"
					v-for="(item,index) in city_list" :key="index">
					{{item.title}}
				</view>
				<view
					@tap.stop="$util.goUrl({url:`/user/pages/choose/city?type=${options.type}`,openType:`redirectTo`})"
					class="list-item flex-y-center f-desc c-base mb-md" :style="{background:primaryColor}"
					v-if="have_more">
					全部城市<i class="iconfont icon-right text-bold"></i>
				</view>
			</view>
		</view>
		<view class="space-footer"></view>

		<!-- #ifdef MP-WEIXIN -->
		<user-privacy ref="user_privacy" :show="false"></user-privacy>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<longbingbing-app-check-auth type="location" ref="app_check_item"
			@confirm="toResetLoca(1)"></longbingbing-app-check-auth>
		<!-- #endif -->

	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		data() {
			return {
				isLoad: false,
				options: {},
				address_list: [],
				city_list: [],
				have_more: 0,
				prePage: '',
				initLoca: {
					lat: 0,
					lng: 0
				}
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			technicianParam: state => state.technician.param,
		}),
		async onLoad(options) {
			let {
				type = 0,
					isloca = 0,
			} = options
			type = type * 1
			isloca = isloca * 1
			options.type = type
			options.isloca = isloca
			this.options = options
			this.$util.setNavigationBarColor({
				bg: this.primaryColor,
				color: '#000000'
			})
			uni.setNavigationBarTitle({
				title: `选择服务地址`
			})
			if (!isloca) { 
				await this.$util.getCoachUtilLoca(false)
			}
			// #ifdef H5
			this.$jweixin.initJssdk(() => {
				this.$jweixin.hideOptionMenu()
			})
			// #endif
		},
		onShow() {
			this.initIndex()
		},
		methods: {
			...mapActions(['getConfigInfo', 'getCityList']),
			...mapMutations(['updateUserItem', 'updateServiceItem', 'updateTechnicianItem',
				'updateMapItem', 'updateShopstoreItem', 'updateDynamicItem'
			]),
			async initIndex(refresh = false) {
				let code = ''
				// #ifdef H5
				code = this.$util.getQueryString('code')
				// #endif 
				let {
					id: uid = 0
				} = this.userInfo
				if (code && !uid) {
					await this.getConfigInfo()
				}
				let {
					lat,
					lng,
					address: addr = '',
					address_info = ''
				} = this.location
				if (lat && lng && !addr && !address_info) {
					await this.$util.getMapInfo(false, true, {}, true, true)
					await this.getCityList({
						lat,
						lng,
						change: 1
					})
				}
				let {
					address,
					city_list,
					have_more
				} = await this.$api.base.cityData()
				city_list.map(item => {
					item.address = item.title
				})
				this.address_list = address
				this.city_list = city_list
				this.have_more = have_more
				this.isLoad = true
				let pages = getCurrentPages()
				let len = pages.length
				if (len > 1) {
					let {
						route,
					} = pages[len - 2]
					this.prePage = route
				}
			},
			initRefresh() {
				this.initIndex(true)
			},
			async toResetLoca(isReset) {
				let {
					location = {}, city_info = {}
				} = this
				if (!isReset && location && city_info && location.id == city_info.id && location.address == city_info
					.title) {
					this.toChooseLoca(this.city_info)
					return
				}
				if (isReset) {
					// #ifdef MP-WEIXIN
					let privacyCheck = this.$refs.user_privacy.check()
					if (privacyCheck) {
						this.$refs.user_privacy.open()
						return
					}
					await this.$util.checkAuth({
						type: 'userLocation'
					})
					// #endif
					// #ifdef APP-PLUS
					if (plus.os.name == 'Android' && plus.navigator.checkPermission(
							'android.permission.ACCESS_FINE_LOCATION') ===
						'undetermined') {
						this.$refs.app_check_item.open()
						return
					}
					// #endif
					this.$util.showLoading({
						title: `定位中...`
					})
					let location = {}
					try {
						location = await this.$util.getCoachUtilLoca(false)
					} catch (e) {
						this.$util.showToast({
							title: `您已拒绝授权获取定位权限1`
						})
						return
					}
					let {
						lat,
						lng
					} = location
					// #ifdef H5
					let isloca = this.$util.getQueryString('isloca') || 0
					if (!lat && !lng && !isloca) {
						this.$util.showToast({
							title: `未获取到定位信息，请稍候重试`
						})
						setTimeout(() => {
							let {
								type = 0
							} = this.options
							let join = type ? '&' : '?'
							window.location.href = window.location.href.replace("user/pages/choose/index",
								`user/pages/choose/index${join}isloca=1`)
						}, 2000)
						return
					}
					if (!lat && !lng && isloca) { 
						location = await this.$util.getCoachUtilLoca(false)
					}
					// #endif
					this.$util.hideAll()
					if (!location.lat) {
						this.$util.showToast({
							title: `请检查定位权限是否打开`
						})
						return
					}
					this.updateUserItem({
						key: 'location',
						val: location
					})
					this.$util.getMapInfo(false, true, {}, true, true)
					this.$util.showToast({
						title: `刷新成功`
					})
					let updateArr = ['updateServiceItem',
						'updateMapItem', 'updateShopstoreItem', 'updateDynamicItem'
					]
					updateArr.map(item => {
						this[item]({
							key: 'pageActive',
							val: false
						})
					})
					let param = Object.assign({}, this.technicianParam, {
						city_id: 0
					})
					this.updateTechnicianItem({
						key: 'param',
						val: param
					})
				}

				setTimeout(() => {
					if (['pages/technician', 'user/pages/choose-technician'].includes(this.prePage)) {
						this.$util.getPage(-1).getList(1, true)
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					} else {
						if (isReset) {
							this.updateUserItem({
								key: 'city_info',
								val: Object.assign({}, this.city_info, {
									id: 0
								})
							})
						}
						this.$util.goUrl({
							url: ['/pages/technician', '/user/pages/choose-technician'][this.options
								.type
							],
							openType: `reLaunch`
						})
					}
				}, isReset ? 1000 : 0)
			},
			async toSelectAddr(index) {
				let val = this.$util.pick(this.address_list[index], ['lat', 'lng', 'address', 'address_info'])
				let param = Object.assign({}, this.technicianParam, {
					city_id: 0
				})
				this.updateTechnicianItem({
					key: 'param',
					val: param
				})
				this.toChooseLoca(val, 1)
			},
			toSelectCity(index) {
				let val = this.city_list[index]
				let {
					id
				} = val
				this.updateUserItem({
					key: 'city_info',
					val
				})
				let param = Object.assign({}, this.technicianParam, {
					city_id: id
				})
				this.updateTechnicianItem({
					key: 'param',
					val: param
				})
				this.toChooseLoca(val)
			},
			toChooseLoca(val, init_city = 0) {
				this.updateUserItem({
					key: 'location',
					val
				})
				let updateArr = ['updateServiceItem',
					'updateMapItem', 'updateShopstoreItem', 'updateDynamicItem'
				]
				updateArr.map(item => {
					this[item]({
						key: 'pageActive',
						val: false
					})
				})
				if (['pages/technician', 'user/pages/choose-technician'].includes(this.prePage)) {
					this.$util.getPage(-1).toChooseLocation(init_city)
					this.$util.goUrl({
						url: 1,
						openType: `navigateBack`
					})
				} else {
					if (init_city) {
						this.updateUserItem({
							key: 'city_info',
							val: Object.assign({}, this.city_info, {
								id: 0
							})
						})
					}
					this.updateUserItem({
						key: 'changeAddr',
						val: true
					})
					this.$util.goUrl({
						url: ['/pages/technician', '/user/pages/choose-technician'][this.options.type],
						openType: `reLaunch`
					})
				}
			}
		},
		filters: {
			handleAddrText(val) {
				let text = `定位中...`
				if (val && val.lat) {
					let {
						address = '',
							address_info = ''
					} = val
					if (address || address_info) {
						if (!address_info) {
							let arr = address.split(' ')
							address_info = arr[arr.length - 1]
						}
						text = address_info
					}
				}
				return text
			},
			handleCityText(val) {
				let text = `未知城市`
				if (val && val.title) {
					text = val.title
				}
				return text
			}
		}
	}
</script>

<style lang="scss">
	.user-pages-choose-index {

		.choose-bg {
			width: 100%;
			height: 265rpx;
			top: 0;
			left: 0;
		}

		.icon-right {
			font-size: 20rpx;
		}

		.default-btn {
			width: 68rpx;
			height: 44rpx;
			border-radius: 8rpx;
			border: 1rpx solid #fff;
		}

		.default-btn.abs {
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			opacity: 0.1;
		}

		.default-btn.md {
			width: 280rpx;
			height: 76rpx;
			border-radius: 10rpx;
		}

		.list-item {
			min-width: 135rpx;
			height: 72rpx;
			padding: 0 15rpx;
			background: #F5F5F5;
			border-radius: 36rpx;
		}
	}
</style>